/*
 * Copyright (c) 2020 pig4cloud Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.pig4cloud.pig.auth.support.handler;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import com.pig4cloud.pig.admin.api.entity.SysLog;
import com.pig4cloud.pig.common.core.constant.CommonConstants;
import com.pig4cloud.pig.common.core.constant.SecurityConstants;
import com.pig4cloud.pig.common.core.util.SpringContextHolder;
import com.pig4cloud.pig.common.log.event.SysLogEvent;
import com.pig4cloud.pig.common.log.util.SysLogUtils;
import com.pig4cloud.pig.common.security.component.PigCustomOAuth2AccessTokenResponseHttpMessageConverter;
import com.pig4cloud.pig.common.security.service.PigUser;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServletServerHttpResponse;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.core.OAuth2AccessToken;
import org.springframework.security.oauth2.core.OAuth2RefreshToken;
import org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse;
import org.springframework.security.oauth2.server.authorization.authentication.OAuth2AccessTokenAuthenticationToken;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.util.CollectionUtils;

import java.io.IOException;
import java.time.temporal.ChronoUnit;
import java.util.Map;

/**
 * 认证成功事件处理器
 * <p>
 * 该类实现了 Spring Security 的 AuthenticationSuccessHandler 接口，
 * 用于处理 OAuth2 认证成功事件。
 * 
 * 主要功能：
 * 1. 记录登录成功日志（用户名、登录耗时等）
 * 2. 发布异步日志事件到系统日志服务
 * 3. 构建 OAuth2 令牌响应
 * 4. 返回标准化的 OAuth2 令牌响应给客户端
 * 
 * 响应内容包括：
 * - access_token：访问令牌
 * - refresh_token：刷新令牌
 * - token_type：令牌类型
 * - expires_in：过期时间
 * - scope：授权范围
 * - 额外参数：用户信息等
 *
 * @author lengleng
 * @date 2025/05/30
 */
@Slf4j
public class PigAuthenticationSuccessEventHandler implements AuthenticationSuccessHandler {

	/**
	 * OAuth2 访问令牌响应消息转换器
	 * 用于将 OAuth2AccessTokenResponse 对象转换为 HTTP 响应
	 */
	private final HttpMessageConverter<OAuth2AccessTokenResponse> accessTokenHttpResponseConverter = new PigCustomOAuth2AccessTokenResponseHttpMessageConverter();

	/**
	 * 用户认证成功时调用
	 * <p>
	 * 处理流程：
	 * 1. 从认证信息中提取用户信息
	 * 2. 记录登录成功日志
	 * 3. 计算登录耗时
	 * 4. 发布异步日志事件
	 * 5. 构建并发送 OAuth2 令牌响应
	 * 
	 * @param request 触发认证成功的请求
	 * @param response 响应对象
	 * @param authentication 认证过程中创建的认证对象，包含令牌和用户信息
	 */
	@SneakyThrows
	@Override
	public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
			Authentication authentication) {
		// 将认证对象转换为 OAuth2 访问令牌认证令牌
		OAuth2AccessTokenAuthenticationToken accessTokenAuthentication = (OAuth2AccessTokenAuthenticationToken) authentication;
		Map<String, Object> map = accessTokenAuthentication.getAdditionalParameters();
		
		// 处理登录成功日志
		if (MapUtil.isNotEmpty(map)) {
			// 从额外参数中获取用户信息
			PigUser userInfo = (PigUser) map.get(SecurityConstants.DETAILS_USER);
			log.info("用户：{} 登录成功", userInfo.getName());
			
			// 设置认证上下文（临时使用，后续会清除）
			SecurityContextHolder.getContext().setAuthentication(accessTokenAuthentication);
			
			// 构建系统日志对象
			SysLog logVo = SysLogUtils.getSysLog();
			logVo.setTitle("登录成功");
			
			// 计算登录耗时
			String startTimeStr = request.getHeader(CommonConstants.REQUEST_START_TIME);
			if (StrUtil.isNotBlank(startTimeStr)) {
				Long startTime = Long.parseLong(startTimeStr);
				Long endTime = System.currentTimeMillis();
				logVo.setTime(endTime - startTime);
			}
			
			// 设置日志创建者
			logVo.setCreateBy(userInfo.getName());
			
			// 发布异步日志事件
			SpringContextHolder.publishEvent(new SysLogEvent(logVo));
		}

		// 输出 OAuth2 令牌响应
		sendAccessTokenResponse(request, response, authentication);
	}

	/**
	 * 发送访问令牌响应
	 * <p>
	 * 构建标准的 OAuth2 令牌响应并返回给客户端。
	 * 响应内容包括：
	 * 1. access_token - 访问令牌
	 * 2. token_type - 令牌类型（通常为 Bearer）
	 * 3. expires_in - 令牌过期时间（秒）
	 * 4. refresh_token - 刷新令牌（如果存在）
	 * 5. scope - 授权范围
	 * 6. additional_parameters - 额外参数（如用户信息）
	 * 
	 * 注意：发送响应后会清除安全上下文，保持无状态设计
	 * 
	 * @param request HTTP请求
	 * @param response HTTP响应
	 * @param authentication 认证信息，包含令牌信息
	 * @throws IOException 写入响应时可能抛出 IO 异常
	 */
	private void sendAccessTokenResponse(HttpServletRequest request, HttpServletResponse response,
			Authentication authentication) throws IOException {

		// 从认证对象中提取令牌信息
		OAuth2AccessTokenAuthenticationToken accessTokenAuthentication = (OAuth2AccessTokenAuthenticationToken) authentication;

		OAuth2AccessToken accessToken = accessTokenAuthentication.getAccessToken();
		OAuth2RefreshToken refreshToken = accessTokenAuthentication.getRefreshToken();
		Map<String, Object> additionalParameters = accessTokenAuthentication.getAdditionalParameters();

		// 构建 OAuth2 访问令牌响应
		OAuth2AccessTokenResponse.Builder builder = OAuth2AccessTokenResponse.withToken(accessToken.getTokenValue())
			.tokenType(accessToken.getTokenType())
			.scopes(accessToken.getScopes());
		
		// 计算并设置令牌过期时间
		if (accessToken.getIssuedAt() != null && accessToken.getExpiresAt() != null) {
			builder.expiresIn(ChronoUnit.SECONDS.between(accessToken.getIssuedAt(), accessToken.getExpiresAt()));
		}
		
		// 添加刷新令牌（如果存在）
		if (refreshToken != null) {
			builder.refreshToken(refreshToken.getTokenValue());
		}
		
		// 添加额外参数（如用户信息等）
		if (!CollectionUtils.isEmpty(additionalParameters)) {
			builder.additionalParameters(additionalParameters);
		}
		
		// 构建最终的响应对象
		OAuth2AccessTokenResponse accessTokenResponse = builder.build();
		ServletServerHttpResponse httpResponse = new ServletServerHttpResponse(response);

		// 清除安全上下文
		// OAuth2 是无状态的，每次请求都需要携带令牌
		SecurityContextHolder.clearContext();

		// 将响应写入 HTTP 响应流
		this.accessTokenHttpResponseConverter.write(accessTokenResponse, null, httpResponse);
	}

}
